#include "tcp_server_select.h"  
  
// 初始化
int tcp_server_init(const char *ip, int port, int backlog)
{
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == fd)
        return fd;
    struct sockaddr_in saddr;
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(port);
    saddr.sin_addr.s_addr = inet_addr(ip);
    int ok = 1;
    if (-1 == setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&ok,sizeof ok))
    {
        perror("setsockopt");
         return -1;
    }
    
    if (-1 == bind(fd, (void *)&saddr, sizeof saddr))
        return -1;

    if (-1 == listen(fd, backlog))
        return -1;
    puts("listen...");
    return fd;
}
// 等待连接
int tcp_server_wait(int listenfd)
{
    struct sockaddr_in caddr; // 用来存储连接的客户端的IP PORT
    socklen_t len = sizeof caddr;

    int nfd = accept(listenfd, (void *)&caddr, &len);
    if (-1 == nfd)
        return -1;
    printf("Client %s:%d connected!\n", inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port));
    return nfd;
}
